package com.gan.ganapigateway;

import com.gan.ganapiclient.utils.SignUtil;
import com.gan.ganapicommon.model.entity.InterfaceInfo;
import com.gan.ganapicommon.model.entity.User;
import com.gan.ganapicommon.service.InnerInterfaceInfoService;
import com.gan.ganapicommon.service.InnerUserInterfaceInfoService;
import com.gan.ganapicommon.service.InnerUserService;
import io.netty.handler.codec.http.HttpResponse;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboReference;
import org.reactivestreams.Publisher;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.core.io.buffer.DataBufferFactory;
import org.springframework.core.io.buffer.DataBufferUtils;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.http.server.reactive.ServerHttpResponseDecorator;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

@Slf4j
@Component
public class CustomGlobalFilter implements GlobalFilter, Ordered {

    @DubboReference
    private InnerUserService innerUserService;

    @DubboReference
    private InnerInterfaceInfoService innerInterfaceInfoService;

    @DubboReference
    private InnerUserInterfaceInfoService innerUserInterfaceInfoService;

    private static final List<String> IP_WHITE_LIST = Arrays.asList("127.0.0.1");
    private static final String INTERFACE_HOST = "http://localhost:8123";

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        // 1.请求日志
        ServerHttpRequest request = exchange.getRequest();
        log.info("请求唯一标识：" + request.getId());
        String path = INTERFACE_HOST + request.getPath().value();
        log.info("请求路径：" + path);
        String methos = request.getMethod().toString();
        log.info("请求方法：" + methos);
        log.info("请求参数：" + request.getQueryParams());
        String sourceAddress = request.getLocalAddress().getHostString();
        log.info("请求来源：" + sourceAddress);
        // 2.制作黑白名单
        ServerHttpResponse response = exchange.getResponse();
//        if (!IP_WHITE_LIST.contains(sourceAddress)){
//            response.setStatusCode(HttpStatus.FORBIDDEN);
//            return response.setComplete();
//        }

        // 3.ak,sk鉴权
        //鉴权
        HttpHeaders header = request.getHeaders();
        String accessKey = header.getFirst("accessKey");
        String nonce = header.getFirst("nonce");
        long timestamp = Long.parseLong(header.getFirst("timestamp"));
        String sign = header.getFirst("sign");
        String body = header.getFirst("body");

        // 实际情况是从数据库中查询出secretKey
        User user = innerUserService.getInvokeUser(accessKey);
        String secretKey = user.getSecretKey();
        String serverSign = SignUtil.getSign(body, secretKey);

        if (user == null)
            return handleNoAuth(response);

        if (Long.parseLong(nonce) > 100000) {
            return handleNoAuth(response);
        }
        // 超过一定时间违法
        long currentTime = System.currentTimeMillis() / 1000;//以秒计位
        if (currentTime - timestamp >= 60 * 5L) {
            return handleNoAuth(response);
        }
        if (sign == null || !sign.equals(serverSign)) {
            return handleNoAuth(response);
        }

        // 4.查看接口信息是否存在
        InterfaceInfo interfaceInfo = innerInterfaceInfoService.getInterfaceInfo(path,methos);
        if (interfaceInfo == null)
            handleNoAuth(response);
        // 5.请求转发，调用接口
        // 6.响应日志
        return handleResponse(exchange, chain, interfaceInfo.getId(), user.getId());
    }

    /**
     * 处理响应
     *
     * @param exchange
     * @param chain
     * @return
     */

    public Mono<Void> handleResponse(ServerWebExchange exchange, GatewayFilterChain chain,long interfaceInfoId,long userId) {
        try {
            // 缓存数据工厂
            ServerHttpResponse originalResponse = exchange.getResponse();
            DataBufferFactory bufferFactory = originalResponse.bufferFactory();
            //拿到响应码
            HttpStatus statusCode = originalResponse.getStatusCode();

            if (statusCode == HttpStatus.OK) {
                // 装饰增强能力
                ServerHttpResponseDecorator decoratedResponse = new ServerHttpResponseDecorator(originalResponse) {

                    @Override
                    public Mono<Void> writeWith(Publisher<? extends DataBuffer> body) {
                        log.info("body instanceof Flux: {}", (body instanceof Flux));
                        if (body instanceof Flux) {
                            Flux<? extends DataBuffer> fluxBody = Flux.from(body);
                            // 往返回值里写数据
                            return super.writeWith(
                                    fluxBody.map(dataBuffer -> {
                                         // 7.响应成功做出处理
                                        try {
                                            innerUserInterfaceInfoService.invokeCount(interfaceInfoId,userId);
                                        } catch (Exception e) {
                                            log.error("invokeCount error" + e);
                                        }
                                        byte[] content = new byte[dataBuffer.readableByteCount()];
                                        dataBuffer.read(content);
                                        DataBufferUtils.release(dataBuffer);//释放掉内存
                                        // 构建 + 输出日志
                                        StringBuilder sb2 = new StringBuilder(200);
                                        sb2.append("<--- {} {} \n");
                                        List<Object> rspArgs = new ArrayList<>();
                                        rspArgs.add(originalResponse.getStatusCode());
                                        String data = new String(content, StandardCharsets.UTF_8);//data
                                        // 打印日志
                                        sb2.append(data);
                                        log.info("响应结果：" + data);
                                        return bufferFactory.wrap(content);
                                    }));
                        } else {
                            // todo 8.调用失败返回规范错误码
                            //handleInvokeError();
                            log.error("<--- {} 响应code异常", getStatusCode());
                        }
                        return super.writeWith(body);
                    }
                };
                // 设置装饰过的response对象
                return chain.filter(exchange.mutate().response(decoratedResponse).build());
            }
            return chain.filter(exchange);//降级处理返回数据
        } catch (Exception e) {
            log.error("网关响应异常" + e);
            return chain.filter(exchange);
        }
    }

    public Mono<Void> handleNoAuth(ServerHttpResponse response) {
        response.setStatusCode(HttpStatus.FORBIDDEN);
        return response.setComplete();
    }

    public Mono<Void> handleInvokeError(ServerHttpResponse response) {
        response.setStatusCode(HttpStatus.FORBIDDEN);
        return response.setComplete();
    }

    @Override
    public int getOrder() {
        return -1;
    }
}
